<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      v-model:search="search"
      v-model:page="page"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
      class="aps-order"
      @current-row-change="handleCurrentRowChange"
    >
      <template #menu-left>
        <el-button type="primary" icon="el-icon-plus" @click="toggleDialogVisible">创建生产工单</el-button>
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.order_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template>
    </avue-crud>
    <add-order ref="addOrder" :dialogVisible="dialogVisible" :order="currentRow" @closeDialog="toggleDialogVisible"/>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/aps/order';
import { mapGetters } from 'vuex';
import { baseUrl } from '@/config/env';
import { nextTick } from 'vue';
import AddOrder from '@/views/aps/components/AddOrder.vue';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 15,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: false,
        searchMenuSpan: 24,
        tip: false,
        border: true,
        index: true,
        addBtn: false,
        viewBtn: true,
        selection: true,
        searchSpan: 24,
        column: [
          {
            label: '订单号',
            prop: 'no',
            rules: [
              {
                required: true,
                message: '请输入订单号',
                trigger: 'blur',
              },
            ],
            search: true,
          },
          {
            label: '客户名称',
            prop: 'client',
            rules: [
              {
                required: true,
                message: '请输入客户名称',
                trigger: 'blur',
              },
            ],
            search: true,
          },
          {
            label: '产品代码',
            prop: 'productCode',
            rules: [
              {
                required: true,
                message: '请输入产品代码',
                trigger: 'blur',
              },
            ],
            search: true,
          },
          {
            label: '数量',
            prop: 'quantity',
            rules: [
              {
                required: true,
                message: '请输入数量',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '最晚交期',
            prop: 'deliveryDate',
            rules: [
              {
                required: true,
                message: '请输入最晚交期',
                trigger: 'blur',
              },
            ],
            type: 'date',
            search: true,
            searchRange: true,
          },
          {
            label: '模式',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=order_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            slot: true,
            prop: 'mode',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入模式类型',
                trigger: 'blur',
              },
            ],
            searchMultiple: true,
            align: 'right',
            // gridRow: true
          },
          {
            label: '状态',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=order_state',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            slot: true,
            prop: 'state',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入状态类型',
                trigger: 'blur',
              },
            ],
            searchMultiple: true,
            align: 'right',
            // gridRow: true
          },
          {
            label: '备注',
            prop: 'remark',
            rules: [
              {
                message: '请输入备注',
                trigger: 'blur',
              },
            ],
          },
        ],
        addBtnText: '创建生产工单',
        highlightCurrentRow: true
      },
      data: [],
      dialogVisible: false,
      currentRow: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.order_add, false),
        viewBtn: this.validData(this.permission.order_view, false),
        delBtn: this.validData(this.permission.order_delete, false),
        editBtn: this.validData(this.permission.order_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    toggleDialogVisible() {
      // console.log(this.currentRow);
      if(this.currentRow && this.currentRow.no) {
        this.dialogVisible = !this.dialogVisible
      } else {
        ElMessage.error('请选择订单')
      }
    },
    handleCurrentRowChange(val) {
      this.currentRow = val
    }
  },
  mounted() {
    // 等待 DOM 渲染完成
    nextTick(() => {
      const container = document.querySelector('.avue-form__group--flex');
      if (!container) {
        console.warn('未找到 .avue-form__group--flex 元素');
        return;
      }

      const isInDot = e => {
        const rect = container.getBoundingClientRect();

        // 计算点击位置相对于容器左上角的坐标
        const clickX = e.clientX - rect.left;
        const clickY = e.clientY - rect.top;

        // 假设你想点击左上角 15x15 区域（模拟伪元素位置）
        const targetArea = { x: 0, y: 0, width: 20, height: 20 };

        return (
          clickX >= targetArea.x &&
          clickX <= targetArea.x + targetArea.width &&
          clickY >= targetArea.y &&
          clickY <= targetArea.y + targetArea.height
        );
      };

      container.addEventListener('click', e => {
        if (isInDot(e)) {
          // 点中了“伪元素视觉区域”
          const btn = document.querySelector('.avue-crud__searchBtn');
          btn && btn.click();
          console.log('点击了“伪元素”区域，切换 searchShow:', this.option.searchShow);
        }
      });

      container.addEventListener('mousemove', e => {
        if (isInDot(e)) {
          container.classList.add('show-x');
        } else {
          container.classList.remove('show-x');
        }
      });
    });
  },
  components: {
    AddOrder
  }
};
</script>

<style lang="scss">
.aps-order {
  //z-index: 1;
  .el-collapse-item__content {
    display: block;
    position: fixed;
    z-index: 999;
    right: 0;
    top: 160px;
    //transform: translate(-2%, 2%);

    .avue-form__group--flex {
      display: block;
      //flex: 25%;
      background-color: rgba(250, 250, 250, 0.9);
      border: 1px solid #ccc;
      border-radius: 10px;
      right: 10px;
      padding: 20px 10px 10px;
      margin-right: 10px;
      position: relative;

      &::before {
        content: ''; /* 必须要有 */
        display: block;
        //flex: 0 0 75%;
        position: absolute;
        left: 5px;
        top: 5px;
        background-color: rgba(250, 90, 90, 0.9);
        background-position: center;
        border-radius: 50%;
        width: 10px;
        height: 10px;
        transition: background-color 0.2s ease;
      }

      &:hover::before {
        background-color: rgba(250, 120, 120, 0.9);
      }

      &::after {
        content: '';
        position: absolute;
        left: 5px;
        top: 5px;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        // 不设置背景色，让它透明，只用于 hover 检测（其实不需要，JS 已控制）
      }

      /* 只有当 show-x 类存在时，才显示 "x" */
      &.show-x::after {
        content: '×';
        color: white;
        font-size: 8px;
        line-height: 10px;
        text-align: center;
        background: none; /* 清除背景，只显示文字 */
        z-index: 2;
      }
    }
  }

  .el-col:last-child {
    display: flex;
    justify-content: flex-end;

    &.avue-form__menu {
      padding: 0;
    }
  }

  .avue-crud__search {
    height: 0;
  }
}
</style>
